﻿angular
	.module('src.folders.folderController', ['src.folders.foldersResource'])
	.controller('FolderController', ['$scope', 'Folders', function ($scope, Folders) {
		Folders.query(function (folders) {
			var _topLevelFolders = topLevelFolders(folders);
			var _length = _topLevelFolders.length;

			for (var i = 0; i < _length; i++) {
				fillChildFolders(folders[i], folders);
			}

			$scope.folders = _topLevelFolders;
		});

		function topLevelFolders(folders) {
			var topLevelFolders = [];
			var length = folders.length;

			for (var i = 0; i < length; i++) {
				if (folders[i].ParentFolderId === null) {
					topLevelFolders.push(folders[i]);
				}
			}

			return topLevelFolders;
		}

		function fillChildFolders(parentFolder, folders) {
			var length = folders.length;

			for (var i = 0; i < length; i++) {
				if ((folders[i].ParentFolderId !== null) && (folders[i].ParentFolderId === parentFolder.FolderId)) {
					parentFolder.ChildFolders.push(folders[i]);
					fillChildFolders(folders[i], folders);
				}
			}
		}
	}]);